<template>
    <!-- pages/wallet/addbankcard/index.wxml -->
    <view>
        <view class="title">请绑定本人银行卡账户</view>
        <view class="cardbox" v-if="checkUserStatus == 5">
            <view class="centers box">
                <view>持卡人姓名</view>
                <view><input @input="getinput" class="widthinput" type="text" :value="name" placeholder="输入您的姓名" /></view>
            </view>
            <view class="centers box">
                <view>持卡人身份证</view>
                <view><input @input="getUserno" class="widthinput" type="idcard" :value="userNo" placeholder="输入您的身份证" /></view>
            </view>
            <view class="centers box" @tap="showgenderFun">
                <view>性别</view>
                <view>
                    <view class="widthinput1">{{ gendername.name }}</view>
                    <view>
                        <image class="icon-32" :src="imgUrl + 'right.png'"></image>
                    </view>
                </view>
            </view>
            <view class="centers box">
                <view>出生年月日</view>
                <view>
                    <view><input @input="getbirthDay" class="widthinput" type="number" :value="birthDay" placeholder="格式：19980527" /></view>
                </view>
            </view>
            <view class="centers box" @tap="showType">
                <view>开户行</view>
                <!-- <view><input bindinput="getCardtype" class="widthinput" type="number" placeholder="请选择开户银行"/></view> -->
                <view>
                    <view class="widthinput1">{{ tsctype }}</view>
                    <view>
                        <image class="icon-32" :src="imgUrl + 'right.png'"></image>
                    </view>
                </view>
            </view>
            <view class="centers box">
                <view>银行卡号</view>
                <view><input @input="getCardnum" class="widthinput" type="number" :value="cardNo" placeholder="输入您的卡号" /></view>
            </view>
            <view class="centers box">
                <view>银行预留手机</view>
                <view><input @input="getPhonenum" class="widthinput" type="number" :value="mobile" placeholder="输入您的手机号" /></view>
            </view>
            <!-- <view class="centers box">
      <view>手机验证码</view>
      <view><input bindinput="getCode" class="widthinput" type="number" placeholder="填写验证码" /></view>
      <view wx:if="{{btnvisible == true}}" class="code" bindtap="onCode">获取验证码</view>
      <view wx:if="{{btnvisible == false}}" class="code"
          disabled="true">{{count_down}}秒</view>
    </view> -->
        </view>
        <view class="cardbox" v-if="checkUserStatus == 1">
            <view class="centers box">
                <view>持卡人姓名</view>
                <view><input @input="getinput" class="widthinput" type="text" :value="name" placeholder="输入您的姓名" /></view>
            </view>
            <view class="centers box">
                <view>开户行</view>
                <!-- <view><input bindinput="getCardtype" class="widthinput" type="number" placeholder="请选择开户银行"/></view> -->
                <view @tap="showType">
                    <view class="widthinput1">{{ tsctype }}</view>
                    <view @tap="showType">
                        <image class="icon-32" :src="imgUrl + 'right.png'"></image>
                    </view>
                </view>
            </view>
            <view class="centers box">
                <view>银行卡号</view>
                <view><input @input="getCardnum" class="widthinput" type="number" :value="cardNo" placeholder="输入您的卡号" /></view>
                <!-- <view><image class="icon-32" src="{{imgUrl + 'camera.png'}}"></image></view> -->
            </view>
            <view class="centers box">
                <view>银行预留手机</view>
                <view><input @input="getPhonenum" class="widthinput" type="number" :value="mobile" placeholder="输入您的手机号" /></view>
            </view>
            <view class="centers box">
                <view>手机验证码</view>
                <view><input @input="getCode" class="widthinput input2" type="number" placeholder="填写验证码" /></view>
                <view v-if="btnvisible == true" class="code" @tap.stop.prevent="onCode">获取验证码</view>
                <view v-if="btnvisible == false" class="code" :disabled="true">{{ count_down }}秒</view>
            </view>
        </view>
        <view class="btn" @tap="onBind">提交</view>

        <van-popup :show="showtype" round position="bottom" custom-style="height: 300px" @close="onCancel" close-icon="cross" closeable>
            <view class="pbox1 mt-100">
                <van-picker
                    show-toolbar
                    title="标题"
                    :columns="showtypeList"
                    @cancel="onCancel"
                    @change="onChangeType"
                    :show-toolbar="false"
                    custom-class="pbox"
                    value-key="bankname"
                    visible-item-count="3"
                    :default-index="defaultindex"
                />
            </view>

            <view class="btn1" @tap="onConfirm">确定</view>
        </van-popup>

        <!-- <van-popup show="{{ showidType }}" round position="bottom" custom-style="height: 300px" bind:close="onCancelidType"
    close-icon="cross" closeable>
    <view class="pbox1 mt-100">
      <van-picker show-toolbar title="标题" columns="{{ genderlist }}" bind:cancel="onCancelidType" bind:change="onChangeidType"
        show-toolbar="{{false}}" custom-class="pbox" value-key="name" visible-item-count="2" />
    </view>

    <view class="btn1" bindtap="onConfirmidType">
      确定
    </view>
  </van-popup> -->

        <van-popup :show="showgender" round position="bottom" custom-style="height: 300px" @close="onCancelgender" close-icon="cross" closeable>
            <view class="pbox1 mt-100">
                <van-picker
                    show-toolbar
                    title="标题"
                    :columns="genderlist"
                    @cancel="onCancel"
                    @change="onChangegender"
                    :show-toolbar="false"
                    custom-class="pbox"
                    value-key="name"
                    visible-item-count="3"
                />
            </view>

            <view class="btn1" @tap="onConfirmgender">确定</view>
        </van-popup>
    </view>
</template>

<script>
// pages/wallet/addbankcard/index.js
const app = getApp(); // 引入app

import _request from '../../../utils/request.js';
export default {
    data() {
        return {
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            showtypeList: [],

            showtype: false,
            tsctype: '请选择开户银行',
            bank: null,
            mobile: '',
            name: '',
            cardNo: '',
            userNo: '',
            code: '',
            oldtsctype: '',
            oldbank: '',
            oldopenBank: '',
            btnvisible: true,
            count_down: 60,
            userObj: null,
            openBank: '',
            birthDay: '',
            showidType: false,
            showgender: false,

            gendername: {
                name: ''
            },

            oldgendername: null,
            goUrl: '',

            genderlist: [
                {
                    name: '男',
                    type: 'M'
                },
                {
                    name: '女',
                    type: 'F'
                }
            ],

            checkUserStatus: '',
            defaultindex: 0,
            oriTransId: '',
            gender: '',

            // MF-男女
            // A大陆身份证 E-港澳居民往来大陆通行证 F-台湾居民往来大陆通行证
            idType: 'A',

            bankcode: '',
            timer: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        let that = this;
        const eventChannel = that.getOpenerEventChannel();
        eventChannel.on('acceptData', function (row) {
            that.setData({
                name: row.custName || '',
                userNo: row.idNo || '',
                checkUserStatus: row.checkUserStatus
            });
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 获取用户已绑定的银行卡列表
        _request
            .get('/settings/getAllBank', {})
            .then((res) => {
                this.setData({
                    showtypeList: res.data.data
                });
            })
            .catch((error) => {
                console.log(error, 'error');
            }); // 实名状态
        // _request.get('/userAuthApply/getApplyStatus', {
        //   userId: wx.getStorageSync('userid')
        // }).then((res) => {
        //   this.setData({
        //     userObj: res.data.data
        //   })
        // }).catch((error) => {
        //   console.log(error, 'error');
        // })
        // 是否在厦门银行实名过 (data=5未实名，1是已实名)

        _request
            .get('/tfs/checkUserStatus', {
                userId: uni.getStorageSync('userid')
            })
            .then((res) => {
                this.setData({
                    checkUserStatus: res.data.data
                });
            });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 性别显示
        showgenderFun() {
            this.setData({
                showgender: true
            }); // 第一次默认选中

            if (this.gendername == '') {
                this.setData({
                    oldgendername: this.genderlist[0]
                });
            }
        },

        // 银行卡关闭
        onCancelgender() {
            this.setData({
                showgender: false
            });
        },

        //  性别确定
        onConfirmgender() {
            this.setData({
                showgender: false,
                gendername: this.oldgendername
            });
        },

        // 获取性别选择类型
        onChangegender(event) {
            const { picker, value, index } = event.detail;
            this.setData({
                oldgendername: value
            });
        },

        // 银行卡显示
        showType() {
            this.setData({
                showtype: true
            }); // 第一次默认选中

            if (this.tsctype == '请选择开户银行') {
                this.setData({
                    defaultindex: 0,
                    oldtsctype: this.showtypeList[0].bankname,
                    oldbank: this.showtypeList[0],
                    oldopenBank: this.showtypeList[0].bankcode
                });
            }
        },

        // 银行卡关闭
        onCancel() {
            this.setData({
                showtype: false
            });
        },

        // 银行卡确定
        onConfirm() {
            this.setData({
                showtype: false,
                tsctype: this.oldtsctype,
                bank: this.oldbank,
                openBank: this.oldopenBank
            });
        },

        // 获取验证码
        onCode() {
            const { bank, name, cardNo, code, tsctype, mobile, openBank, idType, gendername, birthDay, userNo, oriTransId, checkUserStatus } = this;

            if (this.getRule()) {
                _request
                    .postObj('/tfs/bindCardRequest', {
                        userId: uni.getStorageSync('userid'),
                        openBank: openBank,
                        cardNo: cardNo,
                        mobileNo: mobile
                    })
                    .then((res) => {
                        if (res.data.code === 200) {
                            this.setData({
                                oriTransId: res.data.data.transId
                            });
                            this.get_code_settime();
                        } else {
                            uni.showToast({
                                title: res.data.message || '验证码获取失败!',
                                icon: 'none'
                            });
                        }
                    })
                    .catch((error) => {
                        console.log(error, 'error');
                    });
            }
        },

        // 获取银行卡选择类型
        onChangeType(event) {
            const { picker, value, index } = event.detail;
            this.setData({
                defaultindex: index,
                oldtsctype: value.bankname,
                oldbank: value,
                oldopenBank: value.bankcode
            });
        },

        // 持卡人姓名
        getinput(e) {
            let value = e.detail.value;
            this.setData({
                name: value
            });
        },

        // 出生年月日
        getbirthDay(e) {
            let value = e.detail.value;
            this.setData({
                birthDay: value
            });
        },

        // 银行卡号
        getCardnum(e) {
            let value = this.validateNumber(e.detail.value);
            this.setData({
                cardNo: value
            });
        },

        // 身份证卡号
        getUserno(e) {
            let value = e.detail.value;
            this.setData({
                userNo: value
            });
        },

        // 银行预留手机
        getPhonenum(e) {
            let value = this.validateNumber(e.detail.value);
            this.setData({
                mobile: value
            });
        },

        // 手机验证码
        getCode(e) {
            let value = this.validateNumber(e.detail.value);
            this.setData({
                code: value
            });
        },

        // 过滤
        validateNumber(val) {
            return val.replace(/\D/g, '');
        },

        // 绑定提现账户
        onBind() {
            const { bank, name, cardNo, code, tsctype, mobile, openBank, idType, gendername, birthDay, userNo, oriTransId, checkUserStatus } = this;
            let vm = this; // vm.getRule1() && _request.postObj('/tfs/checkUserStatus', {
            //   userId: wx.getStorageSync('userid'),
            //   role: 1,
            //   idNo:cardNo,
            //   custName:name
            // }).then((res) => {
            // 绑定验证 (data=5未实名，1是已实名)

            if (checkUserStatus == 5) {
                if (vm.getRule1()) {
                    _request
                        .postObj('/tfs/tfsRegister', {
                            userId: uni.getStorageSync('userid'),
                            openBank: openBank,
                            cardNo: cardNo,
                            idNo: userNo,
                            mobileNo: mobile,
                            custName: name,
                            idType,
                            gender: gendername.type,
                            birthDay
                        })
                        .then((res) => {
                            if (res.data.code == 200) {
                                let retUrl = res.data.data.retUrl.split('?');
                                let token = retUrl[1].split('=')[1];
                                uni.showToast({
                                    title: '前往验证',
                                    icon: 'none',
                                    duration: 1000
                                });
                                this.setData({
                                    openBank: '',
                                    cardNo: '',
                                    userNo: '',
                                    mobile: '',
                                    name: '',
                                    gendername: '',
                                    birthDay: '',
                                    tsctype: '请选择开户银行',
                                    bankcode: '',
                                    bank: null
                                });
                                uni.navigateTo({
                                    // 跳转到webview页面
                                    url: '/component/verifybankcard/index?url=' + retUrl[0] + '&token=' + token
                                });
                            } else {
                                uni.showToast({
                                    title: res.data.message,
                                    icon: 'none',
                                    duration: 1000
                                });
                            }
                        });
                }
            } else {
                if (vm.getRule()) {
                    _request
                        .postObj('/tfs/bindCardVeri', {
                            userId: uni.getStorageSync('userid'),
                            openBank: openBank,
                            cardNo: cardNo,
                            mobileNo: mobile,
                            oriTransId,
                            phoneDynCode: code
                        })
                        .then((res) => {
                            if (res.data.code == 200) {
                                uni.showToast({
                                    title: '绑定成功',
                                    icon: 'none',
                                    duration: 1000
                                });
                                this.setData({
                                    openBank: '',
                                    cardNo: '',
                                    userNo: '',
                                    mobile: '',
                                    name: '',
                                    gendername: '',
                                    birthDay: '',
                                    tsctype: '请选择开户银行',
                                    bankcode: '',
                                    bank: null
                                });
                                setTimeout(() => {
                                    uni.navigateBack({
                                        //返回上一个页面
                                        delta: 1
                                    });
                                }, 1000);
                            } else if (res.data.code == 403) {
                                uni.showToast({
                                    title: '输入的银行卡号有误，请重新输入',
                                    icon: 'none',
                                    duration: 1000
                                });
                            } else if (res.data.message == 'oriTransId码不能为空!') {
                                uni.showToast({
                                    title: '请输入正确的验证码',
                                    icon: 'none',
                                    duration: 1000
                                });
                            } else {
                                uni.showToast({
                                    title: res.data.message,
                                    icon: 'none',
                                    duration: 1000
                                });
                            }
                        })
                        .catch((error) => {
                            console.log(error, 'error');
                        });
                }
            } // })
        },

        // 验证规则
        getRule1() {
            const { name, bank, cardNo, mobile, idType, gendername, birthDay, userNo } = this;

            if (!name) {
                uni.showToast({
                    title: '请输入姓名',
                    icon: 'none'
                });
                return false;
            } else if (!userNo) {
                uni.showToast({
                    title: '请输入身份证',
                    icon: 'none'
                });
                return false;
            } else if (!gendername) {
                uni.showToast({
                    title: '请选择性别',
                    icon: 'none'
                });
                return false;
            } else if (!birthDay) {
                uni.showToast({
                    title: '请输入出生年月日',
                    icon: 'none'
                });
                return false;
            } else if (!bank) {
                uni.showToast({
                    title: '请选择开户银行',
                    icon: 'none'
                });
                return false;
            } else if (!cardNo) {
                uni.showToast({
                    title: '请输入卡号',
                    icon: 'none'
                });
                return false;
            } else if (!mobile) {
                uni.showToast({
                    title: '请输入手机号',
                    icon: 'none'
                });
                return false;
            } else {
                return true;
            }
        },

        getRule() {
            const { bank, name, cardNo, code, mobile } = this;

            if (!name) {
                uni.showToast({
                    title: '请输入姓名',
                    icon: 'none'
                });
                return false;
            } else if (!bank) {
                uni.showToast({
                    title: '请选择开户银行',
                    icon: 'none'
                });
                return false;
            } else if (!cardNo) {
                uni.showToast({
                    title: '请输入卡号',
                    icon: 'none'
                });
                return false;
            } else if (!mobile) {
                uni.showToast({
                    title: '请输入手机号',
                    icon: 'none'
                });
                return false;
            } // else if(!code){
            //   wx.showToast({
            //     title: '请输入验证码',
            //     icon: 'none'
            //   })
            //   return false
            // }
            else {
                return true;
            }
        },

        //验证码按钮倒计时方法
        get_code_settime(that) {
            var that = this;
            let countDown = that.data.count_down; //获取倒计时初始值

            that.setData({
                //这里把setInterval复制给变量名timer
                timer: setInterval(function () {
                    // 每隔一秒减1
                    countDown--;
                    that.setData({
                        btnvisible: false,
                        //此处用于隐藏验证码点击按钮，使倒计时显示
                        count_down: countDown //倒计时计数
                    }); //当计数为0时，清空定时器，使验证码按钮再次显示

                    if (countDown == 0) {
                        clearInterval(that.data.timer); //清除timer，

                        that.setData({
                            btnvisible: true,
                            count_down: '60'
                        });
                    }
                }, 1000)
            });
        }
    }
};
</script>
<style>
/* pages/wallet/addbankcard/index.wxss */
.title {
    width: 100%;
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 400;
    color: #ff8722;
    text-align: center;
    margin: 30rpx 0;
}

.cardbox {
    width: 710rpx;
    /* height: 434rpx; */
    background: #ffffff;
    box-shadow: 0px 1px 29px 0px rgba(0, 0, 0, 0.04);
    border-radius: 10px;
    margin: 0 20rpx;
}

.btn {
    width: 670rpx;
    height: 90rpx;
    background: #ff8722;
    border-radius: 45px;
    margin: 170rpx 40rpx 0 40rpx;
    font-size: 36rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #f3f3f3;
    line-height: 90rpx;
    text-align: center;
}

.box {
    height: 86rpx;
    border-bottom: 1px sloid #e8e8e8;
    position: relative;
    line-height: 86rpx;
}

.box > view:nth-child(1) {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
    width: 220rpx;
    text-align: left;
    padding-left: 20rpx;
    box-sizing: border-box;
}

.widthinput {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    max-width: 180px;
}

.input2 {
    max-width: 140px;
}

.widthinput1 {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #666666;
    padding: 0;
}

.icon-32 {
    position: absolute;
    right: 20rpx;
    top: 30%;
}

.code {
    width: 142rpx;
    height: 54rpx;
    background: #ebebeb;
    border-radius: 5px;
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #999999;
    line-height: 54rpx;
    text-align: center;
    position: absolute;
    right: 20rpx;
    top: 20%;
}
/* 弹窗 */
.pbox1 {
    height: 360rpx;
}

.pbox2 {
    height: 360rpx;
}

.btn1 {
    width: 400rpx;
    height: 88rpx;
    background: #ff8722;
    border-radius: 22px;
    font-size: 32rx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
    line-height: 88rpx;
    margin: 0 auto;
    margin-top: -30rpx;
    text-align: center;
}

.btn2 {
    width: 400rpx;
    height: 88rpx;
    background: #ff8722;
    border-radius: 22px;
    font-size: 32rx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
    line-height: 88rpx;
    margin: 0 auto;
    margin-top: 50rpx;
    text-align: center;
}

.van-tab--active {
    font-size: 32rpx !important;
}

.pbox2 .van-picker {
    height: 360rpx !important;
}
</style>
